package com.group2.operations.controller;

import com.github.pagehelper.PageInfo;
import com.group2.operations.common.api.ApiResult;
import com.group2.operations.model.Client;
import com.group2.operations.model.Store;
import com.group2.operations.model.User;
import com.group2.operations.model.dto.CountPeopleDTO;
import com.group2.operations.model.vo.ClientInfoVO;
import com.group2.operations.model.vo.StoreInfoVO;
import com.group2.operations.service.ClientService;
import com.group2.operations.service.FlowService;
import com.group2.operations.service.StoreService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.flowable.engine.common.impl.identity.Authentication;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

@RestController
@RequestMapping("/agent")
public class AgentController {
    @Autowired
    private StoreService storeService;
    @Autowired
    private ClientService clientService;
    @Autowired
    private FlowService flowService;

    @GetMapping("/store")
    @RequiresPermissions("agent:store")
    @ApiOperation("显示当前代理商的所有厅店")
    public ApiResult listStores(@RequestParam int pageNum, @RequestParam int pageSize) {
        Subject subject = SecurityUtils.getSubject();
        //获取用户
        User user = (User) subject.getPrincipal();
        //获取用户id
        int uid = user.getId();

        PageInfo<Store> stores = storeService.listAllStores(uid, pageNum, pageSize);
        return ApiResult.success(stores);
    }

    @GetMapping("/client/{sid}")
    @RequiresPermissions("agent:client")
    @ApiOperation("获取当前厅店的所有用户")
    public ApiResult listClients(@PathVariable int sid, @RequestParam int pageNum, @RequestParam int pageSize) {
        PageInfo<Client> clients = clientService.listClientsOfStore(sid, pageNum, pageSize);
        return ApiResult.success(clients);
    }

    @PostMapping("/client/{sid}")
    @RequiresPermissions("agent:client")
    @ApiOperation("厅店添加用户")
    @ApiImplicitParam(name = "vo", dataTypeClass = ClientInfoVO.class, value = "客户信息对象", required = true)
    public ApiResult addClient(@PathVariable int sid, @RequestBody @Valid ClientInfoVO vo) {
        return clientService.addClient(sid, vo);
    }

    @PutMapping("/client/{cid}")
    @RequiresPermissions("agent:client")
    @ApiOperation("修改用户信息")
    @ApiImplicitParam(name = "vo", dataTypeClass = ClientInfoVO.class, value = "客户信息对象", required = true)
    public ApiResult updateClient(@PathVariable int cid, @RequestBody @Valid ClientInfoVO vo) {
        return clientService.updateClient(cid, vo);
    }

    @DeleteMapping("/client/{cid}")
    @RequiresPermissions("agent:client")
    @ApiOperation("删除用户信息")
    public ApiResult deleteClient(@PathVariable int cid) {
        return clientService.deleteClient(cid);
    }

    @PostMapping("/store")
    @RequiresPermissions("agent:store")
    @ApiOperation("提交增加厅店的申请流程")
    public ApiResult addStoreApply(@RequestBody StoreInfoVO vo) {
        Subject subject = SecurityUtils.getSubject();
        //获取用户
        User user = (User) subject.getPrincipal();
        //获取用户名
        String username = user.getName();
        //组织传递的变量
        Map<String, Object> variables = new HashMap<>();
        variables.put("name", vo.getName());
        variables.put("number", vo.getNumber());
        variables.put("phone", vo.getPhone());
        variables.put("address", vo.getAddress());
        variables.put("buildTime", vo.getTime());

        //设置流程发起人
        Authentication.setAuthenticatedUserId(username);
        //发起流程
        ProcessInstance process = flowService.startProcess(variables, "BasicProcess");
        Authentication.setAuthenticatedUserId(null);

        //获取生成的processID
        String processId = process.getId();
        System.out.println(processId);

        //完成流程的第一个任务
        flowService.completeFirstTask(username, "发起流程", processId, "添加厅店申请", process.getStartTime());

        return Objects.isNull(process) ? ApiResult.failed("申请失败") : ApiResult.success("提交申请成功，请等待审核");
    }

    @PutMapping("/store/{sid}")
    @RequiresPermissions("agent:store")
    @ApiOperation("提交改变厅店状态的流程")
    public ApiResult changeStoreStateApply(@PathVariable int sid) {
        Subject subject = SecurityUtils.getSubject();
        //获取用户
        User user = (User) subject.getPrincipal();
        //获取用户名
        String username = user.getName();
        //查询该用户是否还有对该厅店尚未处理的改变状态的请求，若有则不能申请
        if(flowService.haAppliedToChangeState(username, sid)) {
            return ApiResult.failed("对该厅店的请求尚未处理完成，请待其完成后再次申请");
        }
        //获取厅店目前的状态
        boolean state = storeService.getState(sid);
        //组织传递的变量
        Map<String, Object> variables = new HashMap<>();
        variables.put("sid", sid);
        variables.put("targetState", !state);

        //设置流程发起人
        Authentication.setAuthenticatedUserId(username);
        //发起流程
        ProcessInstance process = flowService.startProcess(variables, "BasicProcess");
        Authentication.setAuthenticatedUserId(null);

        //获取生成的processID
        String processId = process.getId();
        System.out.println(processId);

        //完成流程的第一个任务
        flowService.completeFirstTask(username, "发起流程", processId, "改变厅店状态", process.getStartTime());

        return Objects.isNull(process) ? ApiResult.failed("申请失败") : ApiResult.success("提交申请成功，请等待审核");
    }

    @GetMapping("/store/{sid}")
    @RequiresPermissions("agent:store")
    @ApiOperation("获取某个厅店每天新增客户人数的统计")
    public ApiResult countByDay(@PathVariable int sid) {
        List<CountPeopleDTO> list = storeService.countByDay(sid);
        return ApiResult.success(list);
    }


}
